let rdlgtext="";
let dlgtext="";
let isReply=false;
function chat(
  Account,
  UserAgnet,
  nickname,
  avatar,
  jptlogo,
  labelChat = "",
  typeChat = 0,
  text = "",
  chatOptions = ""
) {
  if(isReply){
      vscode.postMessage({
        type: "errorChat",
        msg:"请等待上一次回答结束",
      });
    return;
  }

  let gptChatNewID;
  let gptChatNew;
  let chatreCode;
  let chatjptChat = document.getElementById("chatjptChat");
  let chatre = chatjptChat.value;
  if (chatre) {
    chatjptChat.value = "";
    chatjptChat.style.height = "23px";
  }
  if (text && text.length > 0) {
    if (typeChat >= 300 && typeChat <= 400) {
      chatreCode = "<p>" + chatre + `</p>`;
    } else {
      chatreCode =
        "<p style='margin-bottom: 7px;'>" +
        chatre +
        `</p><pre><code class="hljs language-TypeScript">${
          hljs.highlight(text, { language: "TypeScript" }).value
        }</code></pre>`;
    }
    chatre = chatre + "\n" + text;
  }
  if (typeChat === 90) {
    chatre = labelChat + "\n" + text;
  }
  if (!chatre) {
    return;
  }
  isReply=true;
  $("#messageContainer").append(`
    <div class="mb-2  w-full ">
    <div class="overflow-hidden break-words p-2 rounded-lg msg" style="background-color: hsla(0, 0%, 100%, .04);">
        <div class="size-7 order-first aspect-square shrink-0 p-1 rounded-full flex items-center gap-2 "
            style="width: 100%!important;margin-bottom: 8px;">
            <img src="${avatar}"
                style="border-radius: 10px;">
            <p>${nickname}</p>
        </div>
        ${labelChat ? "<p class='labelChat'>" + labelChat : "<p>"}${
    chatreCode ?? chatre
  }</p>
    </div>
</div>`);
  scrollTop(true);

  gptChatNewID = parseInt(Date.now() / 1000);
  gptChatNew = Date.now();
  $("#messageContainer").append(`<div class="mb-2  w-full ">
     <div class="overflow-hidden break-words p-2  msg" style="border-top-left-radius: 0.5rem; border-top-right-radius: 0.5rem;background-color: hsla(0, 0%, 100%, .04);">
        <div class="size-7 order-first aspect-square shrink-0 p-1 rounded-full flex items-center gap-2 "
            style="width: 100%!important;margin-bottom: 8px;">
              <img src="${jptlogo}">
            <p>Chat吉PT</p>
        </div>
        <div style="background-color: #9b9b9b0f; border-radius: 0.5rem;padding: 8px;margin-bottom:7px" ><h1  onclick="r_ac(this)" style="padding-bottom: 10px;padding-left: 8px; border-bottom: 2px solid var(--vscode-panel-border)">深度思考<span id="timer-ai${gptChatNewID}" style="color:var(--vscode-disabledForeground)"></span></h1>
        <div id="r-ai${gptChatNewID}" style="padding:7px;color:var(--vscode-disabledForeground)"></div>
</div>
        <p id="ai${gptChatNewID}"></p>
    </div>
    <div class="w-full pl-4 pr-4  gap-2 " style="display: flex; justify-content: flex-start;align-items: center;height: 35px;margin-top: 2px;background-color: hsla(0deg 0% 100% / 9%);border-bottom-left-radius: 0.5rem; border-bottom-right-radius: 0.5rem;">
        <div id="aiMsg${gptChatNewID}" style="display: contents;"><svg t="1721549052623" class="fa fa-spinner rotate-icon icon"  viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5832" width="16" height="16"><path d="M827.211075 221.676536m-54.351151 0a54.351151 54.351151 0 1 0 108.702302 0 54.351151 54.351151 0 1 0-108.702302 0Z" fill="#ffffff" p-id="5833"></path><path d="M940.905298 515.399947m-67.086951 0a67.086952 67.086952 0 1 0 134.173903 0 67.086952 67.086952 0 1 0-134.173903 0Z" fill="#ffffff" p-id="5834"></path><path d="M829.755035 810.595334m-78.974766 0a78.974766 78.974766 0 1 0 157.949532 0 78.974766 78.974766 0 1 0-157.949532 0Z" fill="#ffffff" p-id="5835"></path><path d="M534.831643 928.64149m-91.48657 0a91.486571 91.486571 0 1 0 182.973141 0 91.486571 91.486571 0 1 0-182.973141 0Z" fill="#ffffff" p-id="5836"></path><path d="M243.780191 805.955407m-101.902408 0a101.902408 101.902408 0 1 0 203.804816 0 101.902408 101.902408 0 1 0-203.804816 0Z" fill="#ffffff" p-id="5837"></path><path d="M536.623615 107.870315m-107.854315 0a107.854315 107.854315 0 1 0 215.70863 0 107.854315 107.854315 0 1 0-215.70863 0Z" fill="#ffffff" p-id="5838"></path><path d="M243.780191 224.220497m-107.854315 0a107.854315 107.854315 0 1 0 215.70863 0 107.854315 107.854315 0 1 0-215.70863 0Z" fill="#ffffff" p-id="5839"></path><path d="M129.429978 512.008m-102.766395 0a102.766394 102.766394 0 1 0 205.532789 0 102.766394 102.766394 0 1 0-205.532789 0Z" fill="#ffffff" p-id="5840"></path></svg>生成中...</div>
    </div>
</div>`);
 rdlgtext="";
 dlgtext="";
 vscode.postMessage({
    type: "createChat",
    msg:chatre,
    chatType:typeChat ?? 200,
    gptChatNewID:gptChatNewID,
    gptChatNew:gptChatNew,
    chatOptions
  });

}
function scrollTop(isCompulsionTop = false) {
  let scroll_to_bottom = document.getElementById("messageContainer");
  if (isCompulsionTop) {
    scroll_to_bottom.scrollTop = scroll_to_bottom.scrollHeight;
    return;
  }

    scroll_to_bottom.scrollTop = scroll_to_bottom.scrollHeight;
  
}

function getEncode64(str) {
  return btoa(
    encodeURIComponent(str).replace(
      /%([0-9A-F]{2})/g,
      function toSolidBytes(match, p1) {
        return String.fromCharCode("0x" + p1);
      }
    )
  );
}

function removeTags(str) {
  if ((str === null) || (str === "")) {
    return false;
  } else {
    str = str.toString();
  }
  return str.replace(/<[^>]*>/g, "");
}

function onMsg(data, gptChatNew, gptChatNewID,userId,msg) {
  const $aiMsg = $("#aiMsg" + gptChatNewID);
  try {
    const $gptelement = $("#ai" + gptChatNewID);
    const $rgptelement = $("#r-ai" + gptChatNewID);
 

    // 缓存jQuery对象
    const $timerAiElement = $("#timer-ai" + gptChatNewID);
    const $rAiElement = $("#r-ai" + gptChatNewID);
    const $aiElement = $("#ai" + gptChatNewID);

    if (data.choices[0].delta.reasoning_content) {
      rdlgtext += data.choices[0].delta.reasoning_content;
      $timerAiElement.text(` · ${((Date.now() - gptChatNew) / 1000).toFixed(0)}s`);
    }
    
    dlgtext += data.choices[0].delta.content ?? "";


    if (data.choices[0].finish_reason) {
        isReply=false;
        $rAiElement.hide(500).data({ n: 0 });
        
        // 使用模板字符串
        $aiMsg.html( `
            <svg t="1721549221074" class="icon" viewBox="0 0 1024 1024" version="1.1" 
                 xmlns="http://www.w3.org/2000/svg" p-id="8694" width="16" height="16">
                <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64z m0 820c-205.4 0-372-166.6-372-372 0-89 31.3-170.8 83.5-234.8l523.3 523.3C682.8 852.7 601 884 512 884z m288.5-137.2L277.2 223.5C341.2 171.3 423 140 512 140c205.4 0 372 166.6 372 372 0 89-31.3 170.8-83.5 234.8z"
                      p-id="8695" fill="#ffffff"></path>
            </svg>
            回答结束，耗时：${((Date.now() - gptChatNew) / 1000).toFixed(2)}s`);

        hljs.highlightAll();
        const pres = $aiElement.find("pre");
        const btn = `<div class="w-full pl-4 pr-4  gap-2 " style="border-top-left-radius: 0.5rem; border-top-right-radius: 0.5rem;background: #0404043d;display: flex; justify-content:flex-end;align-items: center;height: 35px;border-bottom: 2px solid var(--vscode-panel-border);"><button title="插入代码" class='codeCard' onclick="vscode.postMessage({type:'insert',text:$(this).parent().parent().text()});"><svg t="1721551926703" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7709" width="16" height="16"><path d="M485.052632 431.157895v161.68421H107.789474V431.157895h377.263158m53.894736-53.894737H53.894737v269.473684h485.052631V377.263158zM916.210526 269.473684H269.473684V107.789474h700.631579V53.894737H215.578947v269.473684h754.526316V269.473684zM215.578947 700.631579v269.473684h754.526316v-53.894737H269.473684v-161.68421h700.631579v-53.894737zM970.105263 484.513684L852.075789 366.484211l-38.265263 38.265263L894.113684 485.052632H646.736842v53.894736h247.376842l-80.303158 80.303158 38.265263 38.265263L970.105263 539.486316l-0.538947-0.538948H970.105263V485.052632h-0.538947z" fill="#1296db" p-id="7710"></path></svg></button><button title="复制代码" class='codeCard' onclick="vscode.postMessage({type:'copy',text:$(this).parent().parent().text()});"><svg t="1721552660021" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8848" data-spm-anchor-id="a313x.search_index.0.i15.3f313a815lq0qN" width="16" height="16"><path d="M720 192h-544A80.096 80.096 0 0 0 96 272v608C96 924.128 131.904 960 176 960h544c44.128 0 80-35.872 80-80v-608C800 227.904 764.128 192 720 192z m16 688c0 8.8-7.2 16-16 16h-544a16 16 0 0 1-16-16v-608a16 16 0 0 1 16-16h544a16 16 0 0 1 16 16v608z" p-id="8849" data-spm-anchor-id="a313x.search_index.0.i16.3f313a815lq0qN" class="selected" fill="#1296db"></path><path d="M848 64h-544a32 32 0 0 0 0 64h544a16 16 0 0 1 16 16v608a32 32 0 1 0 64 0v-608C928 99.904 892.128 64 848 64z" p-id="8850" data-spm-anchor-id="a313x.search_index.0.i17.3f313a815lq0qN" class="selected" fill="#1296db"></path><path d="M608 360H288a32 32 0 0 0 0 64h320a32 32 0 1 0 0-64zM608 520H288a32 32 0 1 0 0 64h320a32 32 0 1 0 0-64zM480 678.656H288a32 32 0 1 0 0 64h192a32 32 0 1 0 0-64z" p-id="8851" data-spm-anchor-id="a313x.search_index.0.i18.3f313a815lq0qN" class="selected" fill="#1296db"></path></svg></button></div>`;

        pres.each(function() {
            $(this).prepend(btn);
        });

        vscode.postMessage({
          type: "chatLog",
          uid:userId,
          time:(gptChatNew/1000).toFixed(0),
          dlgtext:dlgtext,
          chat:msg
        });
      
    } else {
        $rgptelement.text(removeTags(marked.parse(rdlgtext)));
        $gptelement.html( marked.parse(dlgtext));
        hljs.highlightAll();
    }
    scrollTop();

    }
    catch(err) {
      vscode.postMessage({
        type: "errorChat",
        msg: err.message,
      });
      $aiMsg.html( `
            <svg t="1721549221074" class="icon" viewBox="0 0 1024 1024" version="1.1" 
                 xmlns="http://www.w3.org/2000/svg" p-id="8694" width="16" height="16">
                <path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64z m0 820c-205.4 0-372-166.6-372-372 0-89 31.3-170.8 83.5-234.8l523.3 523.3C682.8 852.7 601 884 512 884z m288.5-137.2L277.2 223.5C341.2 171.3 423 140 512 140c205.4 0 372 166.6 372 372 0 89-31.3 170.8-83.5 234.8z"
                      p-id="8695" fill="#ffffff"></path>
            </svg>
            回答出错`);
    }
};